<template>
    <div>
      <div class="mui-flex" style="height: 1.8rem">
          <div class="cell">
              <img v-if="headImg===qn_domain"src="../../assets/default_head.png" class="img-logo" alt="" v-model="headImg" @click="changeHeadClick" size="large">
              <img v-else :src="headImg" class="img-logo" alt="" @click="changeHeadClick" size="large">
          </div>
          <div class="cell4" >
              <p class="center-name">{{username}}</p>
          </div>
      </div>
      <div class="small-space-background"></div>

    <yd-cell-group style="padding-left: 10px;">
        <yd-cell-item type="a">
            <img  slot="icon" class="center-img" src="../../assets/centersuozaidi.png">
            <span slot="left" style="font-size: 1.1em">所在地</span>
            <span slot="right" style="font-size: 1.1em">{{location}}</span>
        </yd-cell-item>

        <yd-cell-item arrow>
            <img  slot="icon" class="center-img" src="../../assets/centerjigou.png">
            <span slot="left" style="font-size: 1.1em">机构</span>
            <span slot="right"  @click="selectjigouClick"style="width: 200px; height: 20px;font-size: 1.1em">{{jigou}}</span>
        </yd-cell-item>

        <yd-cell-item href="#" arrow >
            <img  slot="icon" class="center-img" src="../../assets/centerdepa.png">
            <span slot="left" style="font-size: 1.1em">部门</span>
            <span slot="right" @click="selectbumenClick" style="width: 200px; height: 20px;font-size: 1.1em">{{bumen}}</span>
        </yd-cell-item>

        <yd-cell-item arrow href="/revise_phone" type="link">

            <img  slot="icon" class="center-img" src="../../assets/centershoujihao.png">
            <span slot="left" style="font-size: 1.1em">手机号</span>
            <span slot="right" style="font-size: 1.1em" v-model="shoujihao">{{shoujihao}}</span>
        </yd-cell-item>

        <yd-cell-item arrow href="/revise_password" type="link">
            <img  slot="icon" class="center-img" src="../../assets/centermima.png">
            <span slot="left" style="font-size: 1.1em">登录密码</span>
        </yd-cell-item>

        <yd-cell-item arrow href="/revise_contact"  type="link">
            <img  slot="icon" class="center-img" src="../../assets/centercontact.png">
            <span slot="left" style="font-size: 1.1em">联系电话</span>
            <span slot="right" style="font-size: 1.1em" v-model="contact">{{contact}}</span>
        </yd-cell-item>
    </yd-cell-group>

        <div class="buttom-button-part">
        <a style="margin-right: 0.2rem" @click="layoutHandlerClick" href="javascript:;" class="weui-btn weui-btn_plain-default">退出</a>
    </div>
      <yd-actionsheet :items="myItems1" v-model="show1" cancel="取消"></yd-actionsheet>

    </div>
</template>

<script>
    import {loginout,saveHeadImg,getDepartments,modifybumenInfo,modifyInstInfo,uploadQiNiuImage} from "../../pcof/post";
    import {userInfoData,openId,loginWechatCode,qn_domain,password} from '../../globalVariables'
    export default {
        name: "centerInfo",
        data() {
            return {
/*
                // 机构uuid（inst_uuid）,部门(无) name（username用户名) id（useruuid 用户uuid）
*/
                username:JSON.parse(localStorage.getItem(userInfoData)).name,
                headImg: this.qn_domain + JSON.parse(localStorage.getItem(userInfoData)).headImg,
                location:'',
                jigou: JSON.parse(localStorage.getItem(userInfoData)).bankName,
                jigouuuid:JSON.parse(localStorage.getItem(userInfoData)).bankUuid,
                bumen: JSON.parse(localStorage.getItem(userInfoData)).departmentName,
                bumenuuid: JSON.parse(localStorage.getItem(userInfoData)).partnerUuid,
                shoujihao: JSON.parse(localStorage.getItem(userInfoData)).mobile,
                contact: JSON.parse(localStorage.getItem(userInfoData)).contact_number,
                show1:false,
                myItems1: [
                    {
                        label: '拍照',
                        callback: () => {
                            this.$dialog.toast({mes: '咔擦，此人太帅！', timeout: 1000});
                            //注意： callback: function() {} 和 callback() {}  这样是无法正常使用当前this的
                        }
                    },
                    {
                        label: '从相册中选择',
                        callback: () => {
                            this.$dialog.toast({mes: '看到了不该看到的东西！', timeout: 1000});
                        }
                    }
                ],
                serverIds: '',
                images: [],
                qn_domain: '',
            };
        },
        created() {
            this.qn_domain = localStorage.getItem(qn_domain);
            var province;
            if (JSON.parse(localStorage.getItem(userInfoData)).province===null||JSON.parse(localStorage.getItem(userInfoData)).province==='')
            {
                province='';
            }else
            {
                province=JSON.parse(localStorage.getItem(userInfoData)).province;
            }
            var city;
            if (JSON.parse(localStorage.getItem(userInfoData)).city===null||JSON.parse(localStorage.getItem(userInfoData)).city==='')
            {
                city='';
            }else
            {
                city=JSON.parse(localStorage.getItem(userInfoData)).city;
            }

            var district;
            if (JSON.parse(localStorage.getItem(userInfoData)).district===null||JSON.parse(localStorage.getItem(userInfoData)).district==='')
            {
                district='';
            }else
            {
                district=JSON.parse(localStorage.getItem(userInfoData)).district;
            }
            this.location=province+' '+city+' '+district;


            if (JSON.parse(localStorage.getItem(userInfoData)).headImg===null||JSON.parse(localStorage.getItem(userInfoData)).headImg==='')
            {
                this.headImg = this.qn_domain;

            }else
            {
                this.headImg = this.qn_domain + JSON.parse(localStorage.getItem(userInfoData)).headImg;

            }
        },
        methods:{
             changeHeadClick() {
             //headImg 是图片的url
                let that = this;
                wx.chooseImage({
                    count: 1,
                    sizeType: ['compressed'],// 可以指定是原图还是压缩图，默认二者都有
                    sourceType: ['album','camera'], //'album', 'camera' 可以指定来源是相册还是相机，默认二者都有
                    success: function (res) {
                        var localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
                        that.images=[...that.images,...localIds];
                        // that.$dialog.confirm({
                        //     title: '图片选择测试',
                        //     mes: that.images,
                        //     opts: () => {
                        //         that.$dialog.toast({mes: '你点了确定上传', timeout: 1000});
                        //         // wx.uploadImage({
                        //         //     localId: that.images[0].toString(),
                        //         //     isShowProgressTips: 1,
                        //         //     success: function (res) {
                        //         //         that.serverIds = res.serverId;
                        //         //         that.uploadQiNiuImageFunc();
                        //         //     }
                        //         // });
                        //     }
                        // });
                        wx.uploadImage({
                            localId: that.images[0].toString(),
                            isShowProgressTips: 1,
                            success: function (res) {
                                that.serverIds = res.serverId;
                                that.uploadQiNiuImageFunc();
                            }
                        });
                    }
                })
            },
            async uploadQiNiuImageFunc() {
                var response = await uploadQiNiuImage(
                    JSON.parse(localStorage.getItem(userInfoData)).mobile,
                    this.serverIds,
                    localStorage.getItem(openId)
                );
                if (response.data.code === 200) {
                    this.saveHeadImgFunc(response.data.msg);
                } else {
                    this.$dialog.loading.close();
                    this.serverIds = '';
                    this.idx=0;
                    this.$dialog.toast({
                        mes: "上传图片失败，请重试！",
                        icon: 'error',
                        timeout: 1500
                    });
                }
            },
            async saveHeadImgFunc(image) {
                var response = await saveHeadImg(JSON.parse(localStorage.getItem(userInfoData)).mobile,image);
                console.log(response);
                if (response.data.code === 200) {
                    var userInfoObj = JSON.parse(localStorage.getItem(userInfoData));
                    console.log('----------------------before userInfo obj-------------------');
                    console.log(userInfoObj);
                    userInfoObj.headImg = image;
                    localStorage.removeItem(userInfoData);
                    localStorage.setItem(userInfoData,JSON.stringify(userInfoObj));
                    console.log('-------------------after userInfo obj------------------------');
                    console.log(JSON.parse(localStorage.getItem(userInfoData)));
                    this.headImg = this.qn_domain + JSON.parse(localStorage.getItem(userInfoData)).headImg;
                } else {
                    this.$dialog.toast({
                        mes: '修改成功！',
                        timeout: 1500
                    });
                }
            },
            async selectjigouClick (){//选择机构


                if (JSON.parse(localStorage.getItem('insthistorysearch')) === null || JSON.parse(localStorage.getItem('insthistorysearch')) === '') {
                    localStorage.setItem('insthistorysearch', JSON.stringify
                    ([]));
                }


                this.$router.push({name: 'instList',params: {type:'center'}});
            },

            async selectbumenClick() {//修改部门

                var uuid = JSON.parse(localStorage.getItem(userInfoData)).bankUuid;
                var response = await getDepartments(uuid);

                if (response.data.code === 200) {
                    let that = this;
                    var arr = response.data.data;
                    if(arr.length>0) {
                        var newAr = new Array();
                        for (var i = 0; i < arr.length; i++) {
                            var item = response.data.data[i];
                            newAr.push({'label': item.name, 'value': item.uuid});
                        }

                        //模拟数据
                        weui.picker(
                            newAr,
                            {
                                onChange(result) {
                                },
                                async onConfirm(result) {
                                    that.bumen=result[0].label;
                                    that.bumenuuid=result[0].value;
                                    that.modifybumen();
                                },
                            },
                        );
                    }else
                    {
                        this.$dialog.toast({
                            mes: "当前机构未有下属部门！",
                            timeout: 1500
                        });
                        return;

                    }

                } else {

                    this.$dialog.loading.close();
                    this.$dialog.toast({
                        mes: response.data.msg,
                        timeout: 1500
                    });
                }

            },
            async modifybumen()
            {
                var  modifyresponse = await modifybumenInfo(JSON.parse(localStorage.getItem(userInfoData)).mobile,this.bumenuuid);
                console.log(modifyresponse);
                if (modifyresponse.data.code === 200) {

                    var dic=new Array();
                    dic =JSON.parse(localStorage.getItem(userInfoData));
                    var  newdic={};
                    for (var key in dic) {
                        if (key ==='departmentName')
                        {
                            newdic[key]=this.bumen;

                        }else if (key ==='departmentUuid')
                        {
                            newdic[key]=this.bumenuuid;

                        }else
                        {
                            newdic[key] = dic[key];
                        }
                    }
                    localStorage.removeItem(userInfoData);
                    localStorage.setItem(userInfoData,JSON.stringify
                    (newdic));
                    this.$dialog.toast({
                        mes: '修改成功！',
                        timeout: 1500
                    });
                }else
                {
                    this.$dialog.loading.close();
                    this.$dialog.toast({
                        mes: modifyresponse.data.msg,
                        timeout: 1500
                    });
                }
            },
            async layoutHandlerClick() {
                var mobile = JSON.parse(localStorage.getItem(userInfoData)).mobile;
                console.log(mobile);
                this.$dialog.loading.open('退出登录中...');
                var response = await loginout(JSON.parse(localStorage.getItem(userInfoData)).mobile);
                if (response.data.code === 200) {
                    this.$dialog.loading.close();
                    // localStorage.removeItem(openId);
                    localStorage.removeItem('officedata');
                    localStorage.removeItem('voucher');
                    localStorage.removeItem(password);
                    localStorage.removeItem(loginWechatCode);
                    localStorage.clear();
                    this.$router.push({name: 'loginPhone'});
                } else {
                    this.$dialog.loading.close();
                    this.$dialog.toast({
                        mes: response.data.msg,
                        timeout: 1500
                    });
                }
            },
        }
    }
</script>

<style lang="scss">
    .buttom-button-part {
        padding: 0.2rem;
        .weui-btn {
            //margin-bottom: 0.12rem;
            /*padding-top: 0.1rem;*/
            display: flex;
            height: 0.7rem;
            font-size: 1.2em;
        }
    }
    .center-img
    {
        /*width: 0.5rem;*/
        /*height: 0.8rem;*/
         /*margin-top: 0.2rem;*/
        /*background-color: red;*/
    }



</style>